<template>
  <div class="main-div">
    <div class="main-search-div">
      <el-form ref="searchRef"
               :model="searchItem"
               status-icon
               inline>
        <el-form-item label="消息标识" prop="notificationKey" class="main-search-item-3">
          <el-input v-model="searchItem.notificationKey" type="text"/>
        </el-form-item>
        <el-form-item label="消息类型" prop="notificationType" class="main-search-item-3">
          <common-dict-select v-model="searchItem.notificationType" :dict-key="SYSTEM_NOTIFICATION_TYPE"></common-dict-select>
        </el-form-item>
        <el-form-item label="推送渠道" prop="sendWay" class="main-search-item-3">
          <common-dict-select v-model="searchItem.sendWay" :dict-key="SYSTEM_SEND_WAY"></common-dict-select>
        </el-form-item>
        <el-form-item label="是否停用" prop="isStop" class="main-search-item-3">
          <common-dict-select v-model="searchItem.isStop" :dict-key="SYSTEM_NOTIFICATION_IS_STOP"></common-dict-select>
        </el-form-item>
        <el-form-item label="计划时间" prop="timeRange" class="main-search-item-3">
          <el-date-picker
              v-model="searchItem.timeRange"
              type="datetimerange"
              range-separator="至"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" :loading="searchLoading">查询</el-button>
          <el-button @click="reset(searchRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-button-div">
      <el-button type="primary" @click="addFn">新增</el-button>
      <el-popconfirm title="是否删除?" @confirm="delFn">
        <template #reference>
          <el-button type="danger">删除</el-button>
        </template>
      </el-popconfirm>

    </div>
    <div class="main-table-div">
      <common-page-table
          :data="tableData"
          :columns="columns"
          :pagination="pagination"
          :show-border="true"
          :need-one-select="true"
          :show-no="true"
          :loading="tableLoading"
          :show-action="true"
          :action-config="actionConfig"
          @sizeChange="sizeChange"
          @currentChange="currentChange"
          @handle-current-change="handleTableCurrentChange"
      >
        <template #action="{row}">
          <el-button type="primary" size="small" round @click="editFn(row)">编辑</el-button>
          <el-button :type="formatObjToStr(row.isStop) === '0' ? 'danger' : 'primary'" size="small" round @click="changeStopFn(row)">{{formatObjToStr(row.isStop) === '0' ? '停用' : '启用'}}</el-button>
          <el-button type="warning" size="small" round @click="nowSend(row)">立即发送</el-button>
        </template>
      </common-page-table>
    </div>
  </div>
  <notification-save-dialog
      v-model="dialogItem.showDialog"
      :show-dialog="dialogItem.showDialog"
      :dialog-title="dialogItem.dialogTitle"
      :dialog-type="dialogItem.dialogType"
      :relation-id="dialogItem.relationId"
      @handle-closed="handleClosed($event)"
      @handle-close="handleClose($event)"
  >

  </notification-save-dialog>
</template>

<script setup lang="ts">
import {
  SYSTEM_NOTIFICATION_IS_STOP,
  SYSTEM_NOTIFICATION_TYPE, SYSTEM_SEND_WAY
} from "@/constants/dict-constants.ts";
import CommonDictSelect from "@/components/common/CommonDictSelect.vue";
import {onMounted, reactive, ref} from "vue";
import type {FormInstance} from "element-plus";
import {RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import CommonPageTable from "@/components/common/CommonPageTable.vue";
import {
  delNotificationItemReq,
  getNotificationListPageReq, nowSendMessageReq,
  restartNotificationItemReq, stopNotificationItemReq
} from "@/api/admin/notification.ts";
import NotificationSaveDialog from "@/components/manager/notification/NotificationSaveDialog.vue";
import {DIALOG_ADD, DIALOG_EDIT} from "@/constants/common-constant.ts";
import {checkIsNull} from "@/utils/check-utils.ts";
import {elMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import {formatObjToStr} from "@/utils/format-utils.ts";

interface SearchItem {
  notificationKey: string,
  notificationType: string,
  sendWay: string,
  isStop: string,
  timeRange: any,
}

const searchItem: SearchItem = reactive({
  notificationKey: '',
  notificationType: '',
  sendWay: '',
  isStop: '',
  timeRange: [],
})

const searchRef = ref<FormInstance>()

const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const searchLoading = ref(false)
const search = async () => {
  searchList().then();
}

const searchList = async () => {
  searchLoading.value = true

  const timeRange = searchItem.timeRange;
  let planStartTime = ''
  let planEndTime = ''
  if (timeRange && timeRange.length > 0) {
    planStartTime = timeRange[0]
    planEndTime = timeRange[1]
  }
  const params = {
    notificationKey: searchItem.notificationKey,
    notificationType: searchItem.notificationType,
    sendWay: searchItem.sendWay,
    isStop: searchItem.isStop,
    planStartTime: planStartTime,
    planEndTime: planEndTime,
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize
  }
  const res: any = await getNotificationListPageReq(params)
  searchLoading.value = false
  if (res.code === RESPONSE_CODE_SUCCESS) {
    tableData.value = res.data.rows;
    pagination.total = res.data.total
  }
  searchLoading.value = false
}

const tableData = ref<any[]>([])
const columns = [
  {prop: 'notificationKey', label: '消息标识', width: 'auto', fixed: 'left'},
  {prop: 'notificationTitle', label: '消息标题', width: 'auto', align: 'left'},
  {prop: 'notificationContent', label: '消息内容', width: 'auto', align: 'left'},
  {prop: 'notificationTypeLabel', label: '消息类型', width: 'auto'},
  {prop: 'sendWayLabel', label: '发送渠道', width: 'auto'},
  {prop: 'isStopLabel', label: '是否停用', width: 'auto'},
  {prop: 'planStartTime', label: '计划开始时间', width: 'auto'},
  {prop: 'planEndTime', label: '计划结束时间', width: 'auto'},
]
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)
const pagination = reactive({
  currentPage: currentPage.value,
  pageSize: pageSize.value,
  total: total.value
})
const tableLoading = ref<boolean>(false)
const actionConfig = {
  prop: 'action',
  label: '操作',
  width: '250px',
}

const currentRow = ref()
const sizeChange = (val: number) => {
  pageSize.value = val;
  pagination.pageSize = val;

  searchList().then();
}

const currentChange = (val: number) => {
  currentPage.value = val;
  pagination.currentPage = val;

  searchList().then();
}
const handleTableCurrentChange = (row: any) => {
  currentRow.value = row
}

interface DialogItem {
  showDialog: boolean;
  dialogTitle: string;
  dialogType: string;
  relationId: string;
}
const dialogItem: DialogItem = reactive<DialogItem>({
  showDialog: false,
  dialogTitle: '',
  dialogType: '',
  relationId: ''
})

const addFn = () => {
  dialogItem.showDialog = true
  dialogItem.dialogTitle = '新增消息'
  dialogItem.dialogType = DIALOG_ADD
  dialogItem.relationId = ''
}

const delFn = async () => {
  const selectRow = currentRow.value
  if (checkIsNull(selectRow.id)){
    warningMessageTip("请至少选择一条数据");
    return;
  }

  const params = {
    id: selectRow.id
  }
  const res: any = await delNotificationItemReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS) {
    searchList().then()
  }
}

const editFn = (row: any) => {
  dialogItem.showDialog = true
  dialogItem.dialogTitle = '编辑消息'
  dialogItem.dialogType = DIALOG_EDIT
  dialogItem.relationId = row.id
}

const handleClosed = (val: boolean) => {
  dialogItem.showDialog = val
  searchList().then()
}

const handleClose = (val: boolean) => {
  dialogItem.showDialog = val
}

const changeStopFn = async (row: any) => {
  const params = {
    id: row.id
  }
  if (formatObjToStr(row.isStop) === '1'){
    const res: any = await restartNotificationItemReq(params)
    elMessageTip(res.tipType, res.message)
    if (res.code === RESPONSE_CODE_SUCCESS) {
      searchList().then()
    }
  }

  if (formatObjToStr(row.isStop) === '0'){
    const res: any = await stopNotificationItemReq(params)
    elMessageTip(res.tipType, res.message)
    if (res.code === RESPONSE_CODE_SUCCESS) {
      searchList().then()
    }
  }
}

const nowSend = async (row: any) => {
  const params = {
    id: row.id
  }

  const res: any = await nowSendMessageReq(params)
  elMessageTip(res.tipType, res.message)
}

onMounted(async () => {
  searchList().then();
})
</script>

<style scoped>

</style>